<template>
  <el-upload
    :file-list="fileList"
    :action="uploadUrl"
    :before-upload="uploadBeforeUploadHandle"
    :on-success="imgUploadSuccess"
    list-type="picture-card"
    :on-remove="handleRemove"
    :limit="limit"
    :on-exceed="onExceed"
    :class="{'upload-limit': fileList.length >= limit}"
  >
    <i class="el-icon-plus"></i>
  </el-upload>
</template>

<script>
import Cookies from 'js-cookie'

export default {
  props: {
    limit: {
      type: Number,
      default: 1
    },
    // 以&|&分隔的字符串，比如http:xxx.jpg&|&jpg
    value: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      uploadUrl: window.SITE_CONFIG.apiURL + '/sys/oss/upload?token=' + Cookies.get('token'),
      fileList: []
    }
  },
  watch: {
    value (value) {
      // 初始化时候如果value有值，并且fileList没数据，说明是要回显图片
      if (!!value && this.fileList.length === 0) {
        this.fileList = value.split('&|&').map(url => ({ url }))
      }
    },
    fileList: {
      deep: true,
      handler (list) {
        // response.data.src是已上传的真实图片地址
        const url = list.map(item => (item?.response?.data?.src || item.url)).join('&|&')
        this.$emit('input', url)
      }
    }
  },
  methods: {
    // 上传图片之前
    uploadBeforeUploadHandle (file) {
      if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
        this.$message.error('只支持jpg、jpeg、png、gif格式的图片！')
        return false
      }
    },
    imgUploadSuccess (res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.fileList = fileList
    },
    // 移除某张图片
    handleRemove (file, fileList) {
      console.log('1231', file, fileList)
      this.fileList = fileList
    },
    onExceed () {
      this.$message.warning(`最多上传${this.limit}张图片`)
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-limit ::v-deep .el-upload {
  display: none;
}
</style>
